package com.cjk.console.mqtt;

import java.util.ResourceBundle;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cjk.console.enums.EventTopic;
import com.cjk.console.enums.LogTopic;
import com.cjk.foundation.util.PropertyUtil;

public class MqttSubscribeClient {
	
	private final static Logger LOGGER = LoggerFactory.getLogger(MqttSubscribeClient.class);

	public MqttSubscribeClient() {
        connect();
    }

	private void connect() {
		try {
			ResourceBundle bundle = ResourceBundle.getBundle("config/mqtt");
			
			final String clientId = PropertyUtil.parseStringProperty(bundle, "mqtt.subscribe.clientId");
			final String host = PropertyUtil.parseStringProperty(bundle, "mqtt.host");
			final String username = PropertyUtil.parseStringProperty(bundle, "mqtt.username");
			final char[] password = PropertyUtil.parseStringProperty(bundle, "mqtt.password").toCharArray();
			// 创建客户端
			MqttClient client = new MqttClient(host, clientId, new MemoryPersistence());
			// 创建连接参数
			MqttConnectOptions options = new MqttConnectOptions();
			// 设置是否清空session，这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
			options.setCleanSession(true);
			// apache-apollo 用户名
			options.setUserName(username);
			// apache-apollo 密码
			options.setPassword(password);
			// 设置超时时间 单位为秒
			options.setConnectionTimeout(10);
			// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
			options.setKeepAliveInterval(20);
			// 设置回调函数
			client.setCallback(new MqttPushCallback());
			// 开始连接
			client.connect(options);
			// 消息订阅
			String[] topics = new String[7];
			LOGGER.info("mqtt connect success");
			topics[0] = EventTopic.REBOOT_CALLBACK.toString();
			topics[1] = EventTopic.CONFIG_TV_CALLBACK.toString();
			topics[2] = EventTopic.CONFIG_DEVICE_CALLBACK.toString();
			topics[3] = LogTopic.INFORM.toString();
			topics[4] = LogTopic.SYSINFO_LOG.toString();
			topics[5] = LogTopic.FLOW_LOG.toString();
			topics[6] = EventTopic.CREATE_TUNNEL_CALLBACK.toString();
			int[] qos = {2, 2, 2, 2, 2, 2, 2};
			client.subscribe(topics, qos);
			LOGGER.info("mqtt subscribe success");
		} catch (Exception e) {
			LOGGER.error("mqtt connect error：{}", e);
		}
	}

}
